﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Utils.Physics2D.Objects;
using Utils.MathUtilitys;

namespace Utils.Physics2D.Collision
{
    public class LineCollider : CollisionHandler
    {
        Vector2 pA, pB;

        public Vector2 LinePosA { get { return pA; } set { pA = value; } }
        public Vector2 LinePosB { get { return pB; } set { pB = value; } }

        public LineCollider(PhysicsObject owner, Vector2 pA, Vector2 pB)
            : base(owner)
        {
            this.pA = pA;
            this.pB = pB;
        }

        public override bool CheckCollision(PhysicsObject obj, CollisionHandler.DISPLACE displacement)
        {
            if (CollisionUtils.CircleLine(pA, pB, obj.Pos, obj.Radius))
            {
                if (displacement != DISPLACE.NONE)
                {
                    // TODO: testing
                    Vector2 p = obj.Pos;
                    Vector2 ab = pB - pA;
                    Vector2 pushDir;

                    float t = Vector2.Dot(p - pA, ab) / ab.LengthSquared();

                    if (t < 0)
                    {
                        // push away from corner
                        pushDir = p - pA;
                    }
                    else if (t > 1)
                    {
                        pushDir = p - pB;
                    }
                    else
                    {
                        // push away from edge
                        pushDir = p - (pA + ab * t);
                    }

                    float length = pushDir.Length();
                    pushDir.Normalize();
                    pushDir *= obj.Radius - length;

                    PushByDir(obj, displacement, pushDir);
                }
                return true;
            }

            return false;
        }
    }
}
